package com.inspur.edp.bef.bemanager.lowcode;

import io.iec.edp.caf.boot.context.CAFContext;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.core.context.ICAFContextService;
import io.iec.edp.caf.core.session.CafSession;
import io.iec.edp.caf.core.session.ICafSessionService;
import io.iec.edp.caf.core.session.SessionType;
import io.iec.edp.caf.core.session.core.CAFSessionThreadHolder;
import io.iec.edp.caf.tenancy.api.ITenantService;
import io.iec.edp.caf.tenancy.api.entity.Tenant;

import java.util.HashMap;
import java.util.List;
import java.util.function.Consumer;
import org.springframework.security.core.context.SecurityContextHolder;

public class BSessionUtil {

    public static void wrapFirstTenantBSession(Consumer<Tenant> consumer) {
//        ICafSessionService service = SpringBeanUtils.getBean(ICafSessionService.class);
//        ITenantService tenantService = SpringBeanUtils.getBean(ITenantService.class);
//        final String lang = "zh".concat("-CHS");
//        List<Tenant> tenants = tenantService.getAllTenants(lang);
//        if(tenants == null || tenants.isEmpty()) {
//            throw new RuntimeException("不存在有效的租户");
//        }
//
//        CafSession oldSession = CAFContext.current.getCurrentSession();
//        if(oldSession != null) {
//            clearSession();
//        }
//        try {
//            final String user = "ad".concat("min");
//            for (int i = 0; i<tenants.size(); ++i) {
//                Tenant tenant = tenants.get(i);
//                clearSession();
//                CafSession cafSession = service.create(tenant.getId(), user, lang, new HashMap<>(), SessionType.backend);
//                CAFSessionThreadHolder.setCurrentSession(cafSession);
//                ICAFContextService contextService = SpringBeanUtils.getBean(ICAFContextService.class);
//                contextService.setCurrentSU("Bcc");
//
//                consumer.accept(tenant);
//            }
//        } finally {
//            clearSession();
//        }
    }

    private static void clearSession() {
//        CAFSessionThreadHolder.purge();
//        SecurityContextHolder.clearContext();
    }
}
